#include <iostream>
#include <string>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>


typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    // 给客户端返回一个页面
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    std::cout << "body: " << conn->get_request_body() << std::endl;
    websocketpp::http::parser::request req = conn->get_request();
    std::cout << "method: " << req.get_method() << std::endl;
    std::cout << "uri: " << req.get_uri() << std::endl;

    std::string body = "<html><body><h1>hello yss</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type", "text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void wsopen_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket握手成功..." << "\n";
}
void wsclose_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket连接断开..." << "\n";
}
void wsmsg_callback(wsserver_t* svr, websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    std::cout << "wsmsg: " << msg->get_payload() << std::endl;
    std::string rsp = "client say: " + msg->get_payload();
    conn->send(rsp, websocketpp::frame::opcode::text);
}
int main()
{
    // 实例化对象
    wsserver_t wssvr;
    // 设置日志等级
    wssvr.set_access_channels(websocketpp::log::alevel::none);
    // 初始化asio调度器
    wssvr.init_asio();
    wssvr.set_reuse_addr(true);
    // 设置回调函数
    wssvr.set_http_handler(std::bind(http_callback, &wssvr, std::placeholders::_1));
    wssvr.set_open_handler(std::bind(wsopen_callback, &wssvr, std::placeholders::_1));
    wssvr.set_close_handler(std::bind(wsclose_callback, &wssvr, std::placeholders::_1));
    wssvr.set_message_handler(std::bind(wsmsg_callback, &wssvr, std::placeholders::_1, std::placeholders::_2));
    // 设置监听端口
    wssvr.listen(8081);
    // 获取新连接
    wssvr.start_accept();
    // 启动服务
    wssvr.run();
    return 0;
}